﻿#!/usr/bin/python
# coding=utf-8

"""
Created on 20:39:01 20224-06-14

@author: Griza-pc
"""
from cProfile import label
from math import e
import sys
import getopt

import time
#from token import OP
#import openpyxl
import cv2
import numpy as np
import matplotlib.pyplot as plt 
#import pandas as pd 

COMMOM_VESION_STR = """v0.0.1"""
COMMOM_HELP_STR = """
----视频质量分析工具"""+COMMOM_VESION_STR+"""---
[-v][--version] 版本号
[-f][--file]    输入文件绝对地址
[--ss]   视频的起始时间点
[--dur] 持续分析的时间长度
"""

COMMOM_VIDE_FILENAME_STR = str("")
COMMOM_VIDE_START_TS_INT = 0.0
COMMOM_VIDE_DUR_INT = int(sys.maxsize);

def showImgContinuously(img,fps):
    cv2.imshow("image",img)
    return cv2.waitKey((int)(1000/fps))
    
def showOneImg(img):
    cv2.imshow("image",img)
    cv2.waitKey();

def main(file):
   print(f'输入文件：{file}')
   cap = cv2.VideoCapture(file)
   cap.set(cv2.CAP_PROP_POS_MSEC,COMMOM_VIDE_START_TS_INT)
   
   # ret,testImg = cap.read()
   # print(testImg.shape)
   # for frame_ts in range(S_MEDIA_FILE_ANALYZE_BEGIN_TS, S_MEDIA_FILE_ANALYZE_END_TS, S_ANALYZE_INTERNAL):
   #      cap.set(cv2.cap_prop_pos_msec, frame_ts)
   #      first_ret, first_frame = cap.read()
   #      cap.set(cv2.cap_prop_pos_msec, frame_ts + s_analyze_internal)
   #      second_ret, second_frame = cap.read()

   #      f = ssim(first_frame, second_frame)
   #      print(f)
   frameIdx = 0
   currPosList = []
   while True:
       frameIdx += 1
       
       ret,frame = cap.read()
       currPos = cap.get(cv2.CAP_PROP_POS_MSEC)
       if (currPos - COMMOM_VIDE_START_TS_INT) > COMMOM_VIDE_DUR_INT:
           break
       # if(showImgContinuously(frame,30) != -1):
       #     break
       currPosList.append(currPos)
   
   lastPos = currPosList[0]
   diffList = []
   
   for currPos in currPosList[1:]:
       diffList.append((int)(currPos-lastPos))
       lastPos = currPos
  
   #print(diffList)
   
   #显示分析图
   fig = plt.figure(figsize=(20,4))
   ax = fig.add_subplot(111)
   average = np.mean(diffList)
   titleStr = 'Frame interval line chart\n' + str(file).split('\\')[-1]
   yticksList = [0,20,40,60,80,100]
   yticksList.append(average)
   
   ax.set(xlim=[0,len(diffList)], ylim=[1,100], title=titleStr,ylabel='dur(ms)', xlabel='frames')
   plt.yticks(yticksList)
   plt.axhline(y=average,color='r',label='average')
   plt.plot(diffList,label='Frame interval')
   plt.legend()
   plt.show()
   
       
   cap.release()
   cv2.destroyAllWindows()
   
   
if __name__ == '__main__':
    if len(sys.argv) == 1:
        COMMOM_VIDE_FILENAME_STR = r"C:\Users\griza\Videos\工作素材\CPS_20240613_171828.mp4"
        COMMOM_VIDE_START_TS_INT = 20000
        COMMOM_VIDE_DUR_INT = 10000
    else:
        opts,args = getopt.getopt(sys.argv[1:],'hvf:',['help','version','file=','ss=','dur='])
        for optsName,optsValue in opts:
            if optsName in ('-h','--help'):
                print(COMMOM_HELP_STR)
            elif optsName in('-v','--version'):
                print(COMMOM_VESION_STR)
                print(f'Opencv version:{cv2.getVersionString()}')
            elif optsName in('-f','--file'):
                COMMOM_VIDE_FILENAME_STR = optsValue
            elif optsName in('--ss'):
                print("--ss :" + optsValue)
                COMMOM_VIDE_START_TS_INT = int(optsValue)
            elif optsName in('--dur'):
                COMMOM_VIDE_DUR_INT = int(optsValue)
    
    if COMMOM_VIDE_FILENAME_STR != "":
        main(COMMOM_VIDE_FILENAME_STR)

    
